//
//  MBStoryTabbarViewController.m
//  MiBaoTu
//
//  Created by admin on 16/9/27.
//  Copyright © 2016年 com.caesartech15. All rights reserved.
//

#import "MBStoryTabbarViewController.h"
#import "MBSongDetailController.h"
#import "MBSongDetailForIController.h"

#import "MBSpaceCollectionMusicCell.h"
#import "SharePLayerView.h"

#import "MBSongDetailForIpadController.h"
@interface MBStoryTabbarViewController ()<UITableViewDataSource,UITableViewDelegate,MBSpaceCollectionMusicCellDelegate,SharePLayerViewDelegate> {
    UITableView                 *_tableView;
    NSMutableArray              *_mutArr;
    NSInteger                   indexCount;  //歌曲列表页数
    NSMutableDictionary         *_selectCurrentMusicDic; //获取当前选中的cell的音频数据
    NSMutableArray              *fileIDArr;             //已下载歌曲列表
    CLShareManager              *shareView;
    MusicPLayType               musicPlayType;
    UIImageView                 *headerImgView;
}

@end

@implementation MBStoryTabbarViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _mutArr = [[NSMutableArray alloc]init];
    indexCount = 1;
    _selectCurrentMusicDic = [[NSMutableDictionary alloc]init];
    // Do any additional setup after loading the view.
    [self setNavBar];
    [self setupUI];
    [self onLoadNew];
}

- (void)setNavBar
{
    if (_type == MBStoryTabbarType_zuixinshoufa) {
        [self setTitleView:@"最新首发"];
        musicPlayType = MusicPLayType_ZuiXinShouFa;
        [MobClick event:@"STORY_ZXSF" label:@"故事库-最新首发"];
    }
    else  if (_type == MBStoryTabbarType_jingdianerge) {
        [self setTitleView:@"经典儿歌"];
         musicPlayType = MusicPLayType_ErGe;
        [MobClick event:@"STORY_JDEG" label:@"故事库-经典儿歌"];
    }
    else  if (_type == MBStoryTabbarType_renqigushi) {
        [self setTitleView:@"人气故事"];
         musicPlayType = MusicPLayType_GuShi;
        [MobClick event:@"STORY_RQGS" label:@"故事库-人气故事"];
    }
    else  if (_type == MBStoryTabbarType_chengzhangbibei) {
        [self setTitleView:@"成长必备"];
         musicPlayType = MusicPLayType_ChengZhangBiBei;
        [MobClick event:@"STORY_CZBB" label:@"故事库-成长必备"];
    }
    [self setBackItem];
    
    [self setRightPlayerItem];
}

- (void)setupUI {
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, self.view.height) style:UITableViewStylePlain];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:_tableView];
    _tableView.tableHeaderView = [self addTableHeaderView];
    
    [_tableView addLegendHeaderWithRefreshingTarget:self refreshingAction:@selector(onLoadNew)];
    [_tableView addLegendFooterWithRefreshingTarget:self refreshingAction:@selector(onLoadMore)];
    
    shareView = [[CLShareManager alloc] init];
}

- (void)onUpdateUIForView:(UIDeviceOrientation)orientation
{
    _tableView.frame = CGRectMake(0, 0, SCREEN_WIDTH, self.view.height);
    _tableView.tableHeaderView = [self addTableHeaderView];
    [_tableView reloadData];
}

- (UIView *)addTableHeaderView
{
    UIView *bgView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH,ISIPAD?610*PERCEN: 410*PERCEN)];
    
    bgView.backgroundColor = [UIColor whiteColor];
    
    headerImgView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, bgView.width,ISIPAD?500*PERCEN: 300*PERCEN)];
    headerImgView.backgroundColor = [UIColor clearColor];
    headerImgView.image = [UIImage imageNamed:@"space_qzx_bg"];
    [bgView addSubview:headerImgView];
    
    float itemWidth = 340*PERCEN;
    float itemLeft = (ISPortrait?25*PERCEN:(SCREEN_WIDTH-itemWidth*2)/3.);
    float itemJU = (ISPortrait?20*PERCEN:itemLeft);
    if (ISIPAD) {
        itemLeft = 440*PERCEN;
        itemJU =48*PERCEN;
        itemWidth = (bgView.width-itemLeft*2-itemJU)/2.;
    }
    for (int i=0; i<2; i++) {
        UIButton *bt = [UIButton buttonWithType:UIButtonTypeCustom];
        bt.frame = CGRectMake(itemLeft+(itemWidth+itemJU)*i, headerImgView.bottom+20*PERCEN, itemWidth, 70*PERCEN);
        bt.backgroundColor = [UIColor clearColor];
        bt.tag = 7000+i;
        bt.layer.cornerRadius = 5.f;
        bt.layer.masksToBounds = YES;
        bt.layer.borderWidth =1.f;
        bt.layer.borderColor = UIColorFromHex(0x999999).CGColor;
        [bt setTitleColor:UIColorFromHex(0x333333) forState:UIControlStateNormal];
        bt.titleLabel.font = [UIFont systemFontOfSize:14.f];
        [bt addTarget:self action:@selector(onSelectItemAction:) forControlEvents:UIControlEventTouchUpInside];
        [bgView addSubview:bt];
        
        if (i==0) {
            [bt setTitle:@"播放全部" forState:UIControlStateNormal];
        } else {
            [bt setTitle:@"下载全部" forState:UIControlStateNormal];
        }
    }
    
    UIView *lineView = [[UIView alloc]initWithFrame:CGRectMake((ISIPAD?itemLeft:0), bgView.height-1, bgView.width-(ISIPAD?2*itemLeft:0), 1)];
    lineView.backgroundColor = [UIColorFromHex(0x999999)colorWithAlphaComponent:.35];
    [bgView addSubview:lineView];
    
    return bgView;
}

- (void)loadData
{
    //已下载歌曲
    NSArray *downedMusicArr = [UserManager standerDefult].downedMusicArr;
    fileIDArr = [[NSMutableArray alloc]initWithCapacity:downedMusicArr.count];
    for (int i=0; i<downedMusicArr.count; i++) {
        NSDictionary *dic = [downedMusicArr objectAtIndex:i];
        NSString *fileID = [dic objectForKey:@"fileID"];
        [fileIDArr addObject:fileID];
    }

    //接口
    NSString *url = [NSString stringWithFormat:STORY_ZXSF_AUDIOLIST_URL_PATH,[NSString stringWithFormat:@"%ld",indexCount]];
    NSString *bgRrl = [NSString stringWithFormat:STORY_BACKGROUND_URL_PATH,@1];
    
    if (self.type == MBStoryTabbarType_zuixinshoufa) {
        url = [NSString stringWithFormat:STORY_ZXSF_AUDIOLIST_URL_PATH,[NSString stringWithFormat:@"%ld",indexCount]];
        bgRrl = [NSString stringWithFormat:STORY_BACKGROUND_URL_PATH,@1];
    }
    else if (self.type == MBStoryTabbarType_jingdianerge) {
        url = [NSString stringWithFormat:STORY_THREE_CONTAIN_AUDIOLIST_URL_PATH,@"1",[NSString stringWithFormat:@"%ld",indexCount]];
        bgRrl = [NSString stringWithFormat:STORY_BACKGROUND_URL_PATH,@2];
    }
    else if (self.type == MBStoryTabbarType_renqigushi) {
        url = [NSString stringWithFormat:STORY_THREE_CONTAIN_AUDIOLIST_URL_PATH,@"3",[NSString stringWithFormat:@"%ld",indexCount]];
        bgRrl = [NSString stringWithFormat:STORY_BACKGROUND_URL_PATH,@3];
    }
    else if (self.type == MBStoryTabbarType_chengzhangbibei) {
        url = [NSString stringWithFormat:STORY_THREE_CONTAIN_AUDIOLIST_URL_PATH,@"10",[NSString stringWithFormat:@"%ld",indexCount]];
        bgRrl = [NSString stringWithFormat:STORY_BACKGROUND_URL_PATH,@4];
    }
    
    [[HTTPManager standerDefault]AFGetRequest:url view:nil success:^(NSDictionary *json) {
        [_tableView.header endRefreshing];
        [_tableView.footer endRefreshing];
        
        if ([json isKindOfClass:[NSDictionary class]]) {
            if ([json[@"ret_code"] integerValue]==0) {
                NSArray *arr = json[@"data"];
                if (arr.count > 0) {
                    if (indexCount == 1) {
                        [_mutArr removeAllObjects];
                    }
                    if (arr.count < 10) {
                        //当前页不足10个，下页数据为空，页数-1
                        indexCount--;
                    }
                    
                    [_mutArr addObjectsFromArray:arr];
                }
                [_tableView reloadData];
            }
//            else {
//                [ErrorMessage showErrorMessage:json[@"message"] inView:self.view];
//            }
        }
    } failure:^(NSError *error) {
        [_tableView.header endRefreshing];
        [_tableView.footer endRefreshing];
    }];

    //背景图片
    [[HTTPManager standerDefault]AFGetRequest:bgRrl view:nil success:^(NSDictionary *json) {
        [_tableView.header endRefreshing];
        [_tableView.footer endRefreshing];
        
        if ([json isKindOfClass:[NSDictionary class]]) {
            if ([json[@"ret_code"] integerValue]==0) {
                NSArray *arr = json[@"data"];
                if (arr.count > 0) {
                    NSDictionary *dic = [arr lastObject];
                    NSString *urlPath = [dic objectForKey:@"PicPath"];
                    NSString *urlPath2 = [dic objectForKey:@"PicPath2"];
                    if (![urlPath isKindOfClass:[NSNull class]]) {
                        if (ISIPAD) {
                               [headerImgView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",MUSIC_PLAY_Url,urlPath2]] placeholderImage:[UIImage imageNamed:@"space_qzx_bg"]];
                        }else{
                            
                        
                        [headerImgView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",MUSIC_PLAY_Url,urlPath]] placeholderImage:[UIImage imageNamed:@"space_qzx_bg"]];
                        
                        }
                        [_tableView reloadData];
                    }
                }
                
            }
        }
    } failure:^(NSError *error) {
        [_tableView.header endRefreshing];
        [_tableView.footer endRefreshing];
    }];
    
}

- (void)onLoadNew
{
    indexCount = 1;
    [self loadData];
}

- (void)onLoadMore
{
    ++indexCount;
    [self loadData];
}

#pragma mark - 播放器
- (void)onSelectItemForWork
{
    [self onPlayMusic];
}

#pragma mark - 播放全部、下载全部
- (void)onSelectItemAction:(UIButton *)bt
{
    switch (bt.tag-7000) {
        case 0:
        {
            //全部播放,第一个开始
            if (_mutArr.count > 0) {
                [[UserManager standerDefult]playMusicWithMusicArray:_mutArr withCurrentIndex:0 withMusicPlayType:musicPlayType];
            }
        }
            break;
        case 1:
        {
            //下载
            
            for (int i=0; i<_mutArr.count; i++) {
                 NSDictionary *dic = [_mutArr objectAtIndex:i];
                [[UserManager standerDefult]downLoadMusic:dic withRequestArr:fileIDArr];
            }
            [ErrorMessage showErrorMessage:@"开始下载" inView:self.view];
            
        }
            break;
            
        default:
            break;
    }
}

#pragma mark - cell更多
- (void)onSelectItemForGouXuanWithValue:(id)value WithSelect:(BOOL)isSelect WithView:(MBSpaceCollectionMusicCell *)view
{
    
}
- (void)onSelectItemForMoewWithValue:(NSDictionary *)value withView:(MBSpaceCollectionMusicCell *)view
{
    if (value) {
        [_selectCurrentMusicDic removeAllObjects];
        [_selectCurrentMusicDic addEntriesFromDictionary:value];
        
        NSString *musicID = [NSString stringWithFormat:@"%@",[_selectCurrentMusicDic objectForKey:@"ID"]];
        
        SharePLayerView *show = [[SharePLayerView alloc]initWithFrame:CGRectZero withType:([fileIDArr containsObject:musicID] ? ShowPlayerType_stroyTabbar : ShowPlayerType_stroyCellMore)];
        show.delegate = self;
        show.orientation = self.orientation;
        [show onShowInWindow];
    }
}

#pragma mark - 播放、分享、已下载
//播放
- (void)onSelctItemForMorePlayMusic:(SharePLayerView *)view
{
    if ([[_selectCurrentMusicDic objectForKey:@"AudioStatus"] intValue] == 0) {
//        return;
    }
    if (_selectCurrentMusicDic.allKeys.count == 0) {
        //第一次
        [[UserManager standerDefult]playMusicWithMusicArray:_mutArr withCurrentIndex:0 withMusicPlayType:musicPlayType];
    } else if ([_mutArr containsObject:_selectCurrentMusicDic]) {
        int index = (int)[_mutArr indexOfObject:_selectCurrentMusicDic];
        //当前页面播放
        [[UserManager standerDefult]playMusicWithMusicArray:_mutArr withCurrentIndex:index withMusicPlayType:musicPlayType];
    }
}



//分享
- (void)onSelctItemForMoreShareMusic:(SharePLayerView *)view
{
    
    NSString *audioName = [_selectCurrentMusicDic objectForKey:@"AudioName"];
    audioName = [[audioName componentsSeparatedByString:@"."]firstObject];
    [shareView setShareVC:self content:[NSString stringWithFormat:@"分享:%@",audioName] image:[UIImage imageNamed:@"logo_dl_29"] url:[NSString stringWithFormat:SHARE_MUSIC_URL_PATH,[_selectCurrentMusicDic objectForKey:@"ID"]]];
    [shareView addAudioId:[NSString stringWithFormat:@"%@",[_selectCurrentMusicDic objectForKey:@"ID"]] withType:@1];
    [shareView show];
}
//下载
- (void)onSelctItemForMoreDownMusic:(SharePLayerView *)view
{
    /*
     测试下载地址：
     @"http://dldir1.qq.com/qqfile/QQforMac/QQ_V4.2.4.dmg", 29.5M
     @"http://baobab.wdjcdn.com/1456117847747a_x264.mp4",
     @"http://baobab.wdjcdn.com/14525705791193.mp4",
     @"http://baobab.wdjcdn.com/1456459181808howtoloseweight_x264.mp4",
     @"http://baobab.wdjcdn.com/1455968234865481297704.mp4"
     int des = [[_selectCurrentMusicDic objectForKey:@"ID"]intValue];
     if (des == 1) {
     urlPath = @"http://dldir1.qq.com/qqfile/QQforMac/QQ_V4.2.4.dmg";
     }
     else if (des == 2) {
     urlPath = @"http://baobab.wdjcdn.com/1456117847747a_x264.mp4";
     }
     else if (des == 3) {
     urlPath = @"http://baobab.wdjcdn.com/14525705791193.mp4";
     }
     else if (des == 4) {
     urlPath = @"http://baobab.wdjcdn.com/1456459181808howtoloseweight_x264.mp4";
     }
     else if (des == 5) {
     urlPath = @"http://baobab.wdjcdn.com/1455968234865481297704.mp4";
     }
     */
    if (view.type == ShowPlayerType_stroyCellMore) {        
        [[UserManager standerDefult]downLoadMusic:_selectCurrentMusicDic withRequestArr:fileIDArr];
        [ErrorMessage showErrorMessage:@"开始下载" inView:self.view];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - UITableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _mutArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath\
{
    //歌曲
    static NSString *cellID = @"Collection_Music_Cell";
    MBSpaceCollectionMusicCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    if (!cell) {
        cell = [[MBSpaceCollectionMusicCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        cell.delegate = self;
    }
    //是否隐藏更多按钮
    cell.isHideMoewBt = NO;
//    [cell onCompileCellForLayout:self.isCompiling WithAllSelct:self.isAllSelcting];
    cell.isShowPlayCount = YES;
    
    //value
    NSDictionary *dic = [_mutArr objectAtIndex:indexPath.row];
    cell.dateDic = dic;
    if ([fileIDArr containsObject:[NSString stringWithFormat:@"%@",[dic objectForKey:@"ID"]]]) {
        cell.isShowDowned = YES;
    } else {
        cell.isShowDowned = NO;
    }
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (ISIPAD) {
        return 120*PERCEN;
    }
    return 100*PERCEN;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *dic = [_mutArr objectAtIndex:indexPath.row];
    if ([[dic objectForKey:@"AudioStatus"] intValue] == 0) {
//        return;
    }
    
    if (_selectCurrentMusicDic.allKeys.count == 0) {
        //第一次
        [[UserManager standerDefult]playMusicWithMusicArray:_mutArr withCurrentIndex:indexPath.row withMusicPlayType:musicPlayType];
    } else if ([UserManager standerDefult].selectMusicIndex != indexPath.row) {
        //当前页面播放
        [[UserManager standerDefult]playMusicWithMusicArray:_mutArr withCurrentIndex:indexPath.row withMusicPlayType:musicPlayType];
    } else {
        //2次点击进入播放页面
        if ([UserManager standerDefult].musicArr.count > 0) {
            //歌曲列表没歌曲 无需进入
            UserManager *manager = [UserManager standerDefult];
            [manager setSelectMusicIndex:indexPath.row];
            if (manager.audioPlayerType != AudioPLayerType_YinPin) {
                [manager setIsPlaying:NO];
                [manager setAudioPlayerType:AudioPLayerType_YinPin];
            } else {
                [manager setIsPlaying:YES];
            }

            if (ISIPAD) {
                MBSongDetailForIpadController*song=[[MBSongDetailForIpadController alloc]init];
                [self.navigationController pushViewController:song animated:YES];
                return;
            }
            
            MBSongDetailController *song = [[MBSongDetailController alloc]init];
            [self.navigationController pushViewController:song animated:YES];
        }
    }
    [_selectCurrentMusicDic removeAllObjects];
    [_selectCurrentMusicDic addEntriesFromDictionary:dic];
}

@end
